<template>
    <div class="edu-page-warp">
        <ConditionCard
            shadow="never"
            body-style="padding: 24px 24px 6px 24px;"
            @search="onSubmit"
            @reset="reset('queryForm')"
        >
            <el-form ref="queryForm" :model="queryForm" label-position="right" label-width="90px">
                <el-row :gutter="24" style="height: 50px;">
                    <!-- <el-col :span="8">
                        <el-form-item label="年级:" prop="grade">
                            <el-date-picker
                                v-model="queryForm.grade"
                                value-format="yyyy"
                                type="year"
                                placeholder="选择学年"
                                style="width: 100%"
                            />
                        </el-form-item>
                    </el-col> -->
                    <el-col :span="8">
                        <el-form-item label="培养层次:">
                            <el-select v-model="queryForm.trainingLevel" style="width: 100%" clearable>
                                <el-option
                                    v-for="item in dialogOptions.trainingLevel"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </ConditionCard>
        <el-card v-loading="loading" shadow="never" body-style="padding: 24px;">
            <div class="edu-opertion-bar">
                <div class="float-right">
                    <el-button
                        type="primary"
                        @click="addCourseCategory()"
                    >{{ $t('common.btn.add') }}</el-button>
                </div>
            </div>
            <!--table -->
            <el-table
                :data="courses"
                stripe
                size="mini"
                tooltip-effect="light" 
            >
                <el-table-column :label="'名称'" show-overflow-tooltip>
                    <template slot-scope="props">{{ props.row.name }}</template>
                </el-table-column>
                <el-table-column :label="$t('dic.trainingLevel')">
                    <template slot-scope="props">{{ props.row.trainingLevelI18n }}</template>
                </el-table-column>
                <el-table-column :label="'年级'" align='center'>
                     <template slot-scope="props">
                         <span v-if="props.row.yearEnd">
                             {{ props.row.yearStart+'-'+props.row.yearEnd }}
                         </span>
                          <span v-else>
                             {{ props.row.yearStart+'-'+'永久' }}
                         </span>
                     </template>
                </el-table-column>
                <el-table-column :label="$t('common.text.operation')" width="180px">
                    <template slot-scope="scope">
                        <el-button
                            type="text"
                            size="mini"
                            @click="editCourseCategory(scope.row)"
                        >课程分类设置</el-button>
                        <el-button
                            type="text"
                            size="mini"
                            @click="editCourse(scope.row)"
                        >{{ $t('common.btn.edit') }}</el-button>
                        <el-button
                            type="text"
                            size="mini"
                            @click="showDeleteCourseCategory(scope.row)"
                        >{{ $t('common.btn.delete') }}</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-row>
                <el-col>
                    <el-pagination
                        :current-page="queryForm.pageNum_"
                        :page-sizes="[20, 40, 80, 100]"
                        :page-size="queryForm.pageSize_"
                        :total="queryForm.total"
                        layout="total, sizes, prev, pager, next, jumper"
                        style="float:right;margin-top:10px"
                        @size-change="handleSizeChange"
                        @current-change="handleCurrentChange"
                    />
                </el-col>
            </el-row>
        </el-card>
        <!-- 添加课程 -->
        <el-dialog
            :title="dialogTitle"
            :visible.sync="showCourseDialog"
            width="40%"
            @close="resetFormValidate()"
            :close-on-click-modal="false"
            :close-on-press-escape="false"
        >
            <el-form
                ref="courseForm"
                :model="courseForm"
                :rules="courseRules"
                label-width="125px"
                label-position="right"
                size="mini"
                class="bg-white"
            >
                <el-row>
                    <el-col :span="20" :offset='2'>
                        <el-form-item
                            :label="'类别名称(中文)：'"
                            prop="name"
                        >
                            <el-input
                                v-model="courseForm.name"
                                type="text"
                                placeholder='请输入名称'
                                style="width:100%"
                                maxlength="32"
                            />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="20" :offset='2'>
                        <el-form-item :label="'培养层次：'" prop="trainingLevel">
                            <el-select
                                v-model="courseForm.trainingLevel"
                                style="width:100%"
                                @change="selectCourseParentId"
                            >
                                <el-option
                                    v-for="item in dialogOptions.trainingLevel"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                    :style="{textIndent:item.indent+'px'}"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="20" :offset='2'>
                        <!-- <el-form-item :label="'年级：'" :prop="dialogTitle == '新增课程分类'?'yearStart':''"> -->
                        <el-form-item :label="'年级：'" prop="yearStart">
                            <el-date-picker
                                v-model="courseForm.yearStart"
                                value-format="yyyy"
                                type="year"
                                placeholder="选择年">
                            </el-date-picker>
                            <span>~</span>
                            <el-date-picker
                                v-model="courseForm.yearEnd"
                                value-format="yyyy"
                                type="year"
                                placeholder="选择年">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <el-row>
                <el-col :span="24">
                    <div class="float-right">
                        <el-button @click="cancelDialog">{{ $t('common.btn.cancel') }}</el-button>
                        <el-button
                            type="primary"
                            @click="confirmDialog"
                        >{{ $t('common.btn.confirm') }}</el-button>
                    </div>
                </el-col>
            </el-row>
        </el-dialog>
    </div>
</template>
<script>
import bus from "common/src/utils/bus";
import { queryDic, findTrainingLevelByProjId } from "common/src/api/dictionary";
import {
    getBclCourseCategoryList,
    addBclCourseLabel,
    deleteBclCourseById,
    updateGrade
}from "common/src/api/culture/bachelor";
import mixin from 'common/src/mixins/index';
const DELETE_TYPE = {
    SINGLE: "SINGLE",
    BATCH: "BATCH"
};
const ELECTIVE_TYPE = {
    // 对话框公共选修的状态类型，-1：不可见，0：select类型，1：文本(课程分类为根节点时，显示select类型，子节点时，显示文本不可修改)
    NO_VISIBLE: -1,
    SELECT: 0,
    TEXT: 1
};
export default {
    name: "bcl-course-category-manage",
    mixins: [mixin],
    data() {
        return {
            loading: false,
            showCourseDialog: false,
            dialogTitle: "",
            isElectiveShow: ELECTIVE_TYPE.NO_VISIBLE,
            isEdit: false,
            queryForm: {
                trainingLevelI18n: "",
                name: "", // 课程名称
                yearStar:null,
                yearEnd:null,
                pageNum_: 1,
                pageSize_: 20,
                total: 0
            },
            courseForm: {
                id: "",
                trainingLevel: "",
                name: "",
                yearStart:'',
                yearEnd:'',
                isElective: "0",
                creditLimit: "0"
            },
            options: {
                trainingLevel: []
            },
            dialogOptions: {
                trainingLevel: [],
                // isElective: []
            },
            courses: [],
            deleteType: "", // 删除类型：单个删除或批量删除
            deleteId: "", // 单个删除项Id
            courseRules: {
                name: [
                    {
                        required: true,
                        message: "请输入课程名称(中文)",
                        trigger: "change"
                    },
                    {
                        min: 2,
                        max: 32,
                        message: "长度在 2 到 32 个字符",
                        trigger: "change"
                    }
                ],
                trainingLevel: [
                    {
                        required: true,
                        message: "请选择培养层次",
                        trigger: "change"
                    }
                ],
                yearStart: [
                    {
                        required: true,
                        message: "请选择年级",
                        trigger: "change"
                    }
                ],
                // yearEnd: [
                //     {
                //         required: true,
                //         message: "请选择年纪",
                //         trigger: "change"
                //     }
                // ]
            }
        };
    },
    mounted: function() {
        bus.$on("updateCurrentManageDeptId", currentManageDeptId => {
            this.queryForm.projId = currentManageDeptId;
            this.initTrainingLevelOptions();
        });
        this.init();
        this.initProjId();
        this.initTrainingLevelOptions();
    },
    methods: {
        initProjId() {
            let currentUser =this.global.currentUser;
            this.queryForm.projId = currentUser.currentManageDptId;
        },
        initTrainingLevelOptions() {
            findTrainingLevelByProjId(this.queryForm.projId).then(res => {
                if (res.code === 200) {
                    this.loadTrainingLevelOptions("trainingLevel", res.data);
                }
            });
        },
        loadTrainingLevelOptions(optionKey, dataObj) {
            this.dialogOptions[optionKey] = [];
            _.each(dataObj, level => {
                this.dialogOptions[optionKey].push({
                    label:
                        "en" === this.$store.getters.language
                            ? level.nameEN
                            : level.nameCN,
                    value: level.code
                });
            });
        },
        init() {
            this.getCourseList();
        },
        reset(ref) {
            this.queryForm.grade = "";
            this.queryForm.trainingLevel = ""
            this.getCourseList();
        },
        onSubmit(){
            this.getCourseList();
        },
        getCourseList(pageNumReset = true) {
            let parms={
                        grade:this.queryForm.grade || "",
                        trainingLevel:this.queryForm.trainingLevel || "",
                        pageNum_:this.queryForm.pageNum_,
                        pageSize_:this.queryForm.pageSize_
                    };
            if (pageNumReset) {
                parms.pageNum_ = 1;
            }
           getBclCourseCategoryList(parms).then(response => {
                if (response.code === 200) {
                    this.queryForm.total = response.data.total_;
                    this.courses = response.data.list.sort(
                        (item1, item2) => item2.createTime - item1.createTime
                    );
                }
            });
        },
        handleSizeChange(val) {
            this.queryForm.pageSize_ = val;
            this.getCourseList();
        },
        handleCurrentChange(val) {
            this.queryForm.pageNum_ = val;
            this.getCourseList(false);
        },
        // 重置课程对话框
        resetCourseDialog() {
            this.courseForm.trainingLevel = "";
            this.courseForm.id = "";
            this.courseForm.name = "";
            this.courseForm.yearEnd = null;
            this.courseForm.yearStart = null;
            this.showCourseDialog = true;
        },
        // 创建课程类别
        addCourseCategory(trainingLevel = "") {
            //this.dialogTitle = this.$t("culture.course.create");
            this.dialogTitle = '新增课程分类';
            this.isEdit = false;
            this.isElectiveShow =trainingLevel === "1"
                    ? ELECTIVE_TYPE.SELECT
                    : ELECTIVE_TYPE.NO_VISIBLE;
            if (trainingLevel === "") {
                this.resetCourseDialog();
            }
        },
        // 编辑课程类别
        editCourseCategory(row) {
            let bclOptionalCourse =  {
                    id:row.id,  
                    name:row.name,
                    trainingLevelI18n:row.trainingLevelI18n,
                    trainingLevel:row.trainingLevel,
                    yearStart:row.yearStart,
                    yearEnd:row.yearEnd
                }
            sessionStorage.setItem("bclOptionalCourse",JSON.stringify(bclOptionalCourse));
            this.$router.push({  //核心语句
                path:'/bclOptionalCourse',   //跳转的路径
                query:{           //路由传参时push和query搭配使用 ，作用时传递参数
                    id:row.id,  
                    name:row.name,
                    trainingLevelI18n:row.trainingLevelI18n,
                    trainingLevel:row.trainingLevel,
                    yearStart:row.yearStart,
                    yearEnd:row.yearEnd
                }
            })
        },
         // 编辑课程分类
        editCourse(row) {
            this.dialogTitle = '编辑课程分类';
            this.courseForm.trainingLevel = row.trainingLevel;
            this.courseForm.id = row.id;
            this.courseForm.name = row.name;
            this.courseForm.yearEnd = row.yearEnd+"";
            this.courseForm.yearStart = row.yearStart+"";
            this.showCourseDialog = true;
        },
        // 删除对话框
        showDeleteCourseCategory(row) {
            const _this = this;
            _this
                .$confirm(
                    _this.$t("common.tips.deleteTips"),
                     "提示",
                    {
                        confirmButtonText: _this.$t("common.btn.confirm"),
                        cancelButtonText: _this.$t("common.btn.cancel"),
                        type: "warning"
                    }
                )
                .then(() => {
                    if (!(row.isLeafNode && row.isLeafNode * 1)) {
                        this.confirmDelete(row);
                    } else {
                        this.$confirm(
                            "确认删除此课程下绑定的子课程吗？",
                            "提示",
                            {
                                confirmButtonText: "确定",
                                cancelButtonText: "取消",
                                type: "warning"
                            }
                        )
                            .then(() => {
                                this.confirmDelete(row);
                            })
                            .catch(err => {
                                console.log(err);
                            });
                    }
                })
                .catch(e => {});
        },
        // 取消对话框课程分类
        cancelDialog() {
            this.showCourseDialog = false;
        },
        resetFormValidate() {
            // 清除表单校验
            this.$refs.courseForm.resetFields();
        },
        // 保存对话框课程分类
        confirmDialog() {
            this.$refs.courseForm.validate(valid => {
                let data;
                if (!valid) {
                    return;
                }
                if(this.courseForm.yearStart && this.courseForm.yearEnd){
                    if(this.courseForm.yearStart>this.courseForm.yearEnd){
                        this.$message({
                                    type: "warning",
                                    message: "开始时间不能小于结束时间"
                                });
                        return;
                    }else{
                        data = {
                            trainingLevel: this.courseForm.trainingLevel,
                            name: this.courseForm.name,
                            yearStart: this.courseForm.yearStart,
                            yearEnd: this.courseForm.yearEnd,
                        };
                    }
                }else{
                     data = {
                        trainingLevel: this.courseForm.trainingLevel,
                        name: this.courseForm.name,
                        yearStart: this.courseForm.yearStart,
                    };
                }
                // 根据courseId判断是创建或更新
                // if (this.courseForm.courseId) {
                //     data["id"] = this.courseForm.courseId;
                //     updateGrade(data).then(response => {
                //         if (response.code === 200) {
                //             this.$message({
                //                 type: "success",
                //                 message: "保存成功"
                //             });
                //             this.showCourseDialog = false;
                //             this.getCourseList();
                //         }
                //     });
                // } else {
                    if(this.dialogTitle == '新增课程分类'){
                        addBclCourseLabel(data).then(response => {
                            if (response.code === 200) {
                                this.$message({
                                    type: "success",
                                    message: "创建成功"
                                });
                                this.showCourseDialog = false;
                                this.getCourseList();
                            }
                        });
                    }else{
                        data.id = this.courseForm.id;
                        updateGrade(data).then(response => {
                            if (response.code === 200) {
                                this.$message({
                                    type: "success",
                                    message: "修改成功"
                                });
                                this.showCourseDialog = false;
                                this.getCourseList();
                            }
                    });
                    }
                }
            // }
            );
        },

        // 确定删除
        confirmDelete(deleteData) {
            let ids = []; 
            if (deleteData.id) {
                deleteBclCourseById(deleteData).then(response => {
                    if (response.code == 200) {
                        this.$message({
                            type: "success",
                            message: "删除成功"
                        });
                        this.getCourseList();
                    }
                });
            }
        }
    }
};
</script>
<style lang="sass" scoped>

</style>
